// miniprogram/pages/admin/order/detail/detail.js
const app = getApp();
const util = require('../../../utils/util');
Page({
  /**
   * 页面的初始数据
   */
  data: {

    hideLog: true,

    payments: [],
    paymentsIndex: 0,
    channelList: ['现金', '微信', '支付宝'],
    channelIndex: 0,

    statusMap: app.globalData.statusMap,
    statusText: app.globalData.statusText
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.login(user => {
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      this.loadItem(options);
    })
  },

  // 页面跳转
  redirect: function (e) {
    let url = e.currentTarget.dataset.value;
    wx.navigateTo({
      url: `${url}?_id=${this.data.order._id}`,
    });
  },

  changeStatus: function (e) {
    const that = this;
    const order = this.data.order;
    // if (!order.logs) {
    //   order.logs = [];
    // }
    // order.logs.push({
    //   time: util.formatTime(new Date()),
    //   user: app.globalData.user.name,
    //   text: `${e.currentTarget.dataset.text}`
    // })
    wx.cloud.callFunction({
      name: 'order',
      data: {
        op: 'changeStatus',
        log: {
          time: util.formatTime(new Date()),
          user: app.globalData.user.name,
          text: `${e.currentTarget.dataset.text}`
        },
        _id: order._id,
        status: parseInt(e.currentTarget.dataset.value),
      },
      success: res => {
        console.log(res);
        that.loadItem(that.options)
      }
    })
  },

  loadItem: function (options) {
    const that = this;
    wx.showNavigationBarLoading();
    app.login(user => {
      wx.cloud.callFunction({
        name: 'crud',
        data: {
          op: 'get',
          table: 'order',
          where: {
            _id: options._id,
            studioid: user.studioid
          }
        },
        success: res => {
          wx.hideNavigationBarLoading();
          if (res.result.data.length > 0) {
            // console.log(res.result.data[0])
            const order = res.result.data[0];
            const statusMap = that.data.statusMap;
            // if (order.getdeposit && order.getbalance){
            //   // 如果收款已结束，不再显示收款按钮
            //   for(var i =0;i<statusMap.length;i++){
            //     let v = statusMap[i];
            //     if (v.actions && v.actions.length > 0 && v.actions[v.actions.length - 1].action == 'cash'){
            //       v.actions.pop();
            //     }
            //   }
            //   this.setData({
            //     order,
            //     statusMap
            //   });
            // }else{
            let payments = order.payments
            if (payments&&payments.length > 0) {
              payments = payments.filter(item => !item.time)
            }
            this.setData({
              order,
              payments
            });
            // }

          } else {
            wx.showModal({
              content: '订单不存在！',
              showCancel: false,
              success: r => {
                wx.navigateBack();
              }
            })
          }
        }
      })
      wx.cloud.callFunction({
        name: 'crud',
        data: {
          op: 'get',
          table: 'team',
          field: {
            name: true
          },
          where: {
            studioid: app.globalData.user.studioid
          }
        },
        success: res => {
          this.setData({
            team: res.result.data
          });
        }
      });
    });
  },
  selectTeam: function (e) {
    const team = this.data.team;
    console.log(team, e)
    // let agenda = this.data.agenda;
    this.setData({
      'payment.cashier': team[e.detail.value]
    });
  },
  // 保存收款
  savePayment: function (e) {
    const that = this;
    let order = this.data.order;
    let payments = order.payments

    console.log(payments.find(obj => obj.title == this.data.payments[this.data.paymentsIndex].title))


    let payment = payments.find(obj => obj.title == this.data.payments[this.data.paymentsIndex].title)

    payment.openid = app.globalData.user._openid;
    payment.user = app.globalData.user.name;
    payment.received = parseInt(payment.amount);
    payment.time = util.formatTime(new Date());
    payment.channel = this.data.channelList[this.data.channelIndex];
    let updateData = {
      _id: order._id,
      payments: payments
    };

    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'update',
        table: 'order',
        data: updateData,
      },
      success: res => {
        wx.showToast({
          title: '数据保存成功',
        })
        that.setData({
          'order.payments': payments,
          payments: payments.filter(item => !item.time),
          paymentsIndex: 0,
          channelIndex: 0
        });
        that.hideModal();
      }
    })

    // const that = this;
    // let payment = this.data.payment;
    // let order = this.data.order;
    // for (var n in e.detail.value) {s
    //   payment[n] = e.detail.value[n]
    // }
    // console.log(payment);
    // payment.openid = app.globalData.user._openid;
    // payment.user = app.globalData.user.nickName;
    // payment.amount = parseInt(payment.amount);
    // payment.time = util.formatTime(new Date());
    // payment.channel = this.data.paymentList[payment.channelIndex];
    // let orderPayment = order.payment;
    // // delete payment.item;
    // if (!orderPayment){
    //   orderPayment = [];
    // }
    // orderPayment.push(payment);
    // let updateData = {_id: order._id, payment: orderPayment, getbalance: order.getbalance, getdeposit:order.getdeposit};

    // if (payment.item[payment.itemIndex].title == '尾款'){
    //   updateData.getbalance = true;
    // }else{
    //   updateData.getdeposit = true;
    // }
    // wx.cloud.callFunction({
    //   name: 'crud',
    //   data: {
    //     op: 'update',
    //     table: 'order',
    //     data: updateData,
    //   },
    //   success: res=>{
    //     wx.showToast({
    //       title: '数据保存成功',
    //     })
    //     that.setData({'order.payment': orderPayment, 'order.getdeposit': !!updateData.getdeposit, 'order.getbalance': !!updateData.getbalance});
    //     that.hideModal();
    //   }
    // })

  },

  // 下拉选择
  paymentItemChange: function (e) {
    this.setData({
      'paymentsIndex': e.detail.value
    });
  },

  payChannelChange: function (e) {
    this.setData({
      'channelIndex': e.detail.value
    })
  },


  removeOrder: function (e) {
    // TODO 废弃订单
    wx.showModal({
      content: '您确定要删除此订单吗？',
      success: res => {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: 'order',
            data: {
              op: 'remove',
              _id: this.data.order._id
            },
            success: rr => {
              let pages = getCurrentPages();
              if (pages.length > 1) {
                pages[pages.length - 2].onLoad(pages[pages.length - 2].options);
              }
              wx.navigateBack();
            }
          })

        }
      }
    })
  },


  cash() {
    const order = this.data.order;
    if (order.getdeposit && order.getbalance) {
      wx.showToast({
        title: '此订单已完成收款',
        icon: 'none'
      })
      return;
    }
    const payment = {
      itemIndex: 0,
      channelIndex: 0,
      item: []
    }
    // 判断之前是否已经收款
    if (!order.getdeposit) {
      payment.item.push({
        title: '定金',
        amount: order.deposit
      });
    }

    if (!order.getbalance) {
      payment.item.push({
        title: '尾款',
        amount: parseInt(order.price) - parseInt(order.deposit)
      })
    }

    this.setData({
      modalname: 'cash',
      payment: payment
    })
  },
  showModal(e) {
    let modalname = e.currentTarget.dataset.modalname
    this.setData({
      modalname
    })
  },
  hideModal() {
    this.setData({
      modalname: null
    });
  },
  makeCall: function (e) {
    // 拨打电话
    console.log(e);
    let phone = e.currentTarget.dataset.value;
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      }).then(res => {
        console.log(res);
      }).catch(e => {

      })
    }
  },
  toggle() {
    let hideLog = this.data.hideLog ? false : true
    this.setData({
      hideLog
    })
  },
  requestSubscribeMessage(e) {
    app.requestOrderSubscribeMessage()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})